﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
using Vote.DataEntity;

namespace Vote.Database.DataAccess
{
    /// <summary>
    /// 
    /// </summary>
    public class AdminUserAccess
    {

        public AdminUserDataEntity Login(string username, string password)
        {

            AdminUserDataEntity entity = new AdminUserDataEntity();
            String sql = @"SELECT * FROM admin WHERE Username=?Username and `Password`=?Password;";

            MySqlParameter[] parms = new MySqlParameter[] { 
                new MySqlParameter("Username", MySqlDbType.String),
                new MySqlParameter("Password", MySqlDbType.String),
            };
            parms[0].Value = username;
            parms[1].Value = password;

            using (MySqlDataReader reader = MySqlHelper.ExecuteReader(MySqlHelper.ConnectionStringManager, CommandType.Text, sql, parms))
            {
                while (reader.Read())
                {
                    entity = new AdminUserDataEntity()
                    {
                        Id = (DBNull.Value == reader["Id"]) ? 0 : Convert.ToInt32(reader["Id"]),
                        Username = reader["Username"].ToString(),
                    };
                }
            }
            return entity;
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="admin"></param>
        /// <returns></returns>
        public Boolean EditAdminuser(AdminUserDataEntity admin)
        {
            Int32 result = 0;
            String sql = @"UPDATE admin SET Username=?Username,`Password`=?Password WHERE Id=?Id;";
            MySqlParameter[] parms = new MySqlParameter[] { 
                new MySqlParameter("Username", MySqlDbType.String),
                new MySqlParameter("Password", MySqlDbType.String),
                new MySqlParameter("Id",MySqlDbType.Int32),
            };
            parms[0].Value = admin.Username;
            parms[1].Value = admin.Password;
            parms[2].Value = admin.Id;
            result = MySqlHelper.ExecuteNonQuery(MySqlHelper.ConnectionStringManager, CommandType.Text, sql, parms);
            return (result > 0);
        }
    }
}
